import { Pipe, PipeTransform } from "@angular/core";
import { LocaleService, TranslationService, Language } from "angular-l10n";

@Pipe({
  name: "timeAgo"
})
export class TimeAgoPipe implements PipeTransform {
  constructor(public locale: LocaleService) {}
  transform(value: any, args?: any): any {
    const ago = args.ago;
    const now = args.now;
    const locale = args.locale;
    return this.format({
      ago,
      now,
      locale
    });
  }
  format(m) {
    const ago = m.ago * 1000;
    const now = m.now * 1000;
    const locale = m.locale;
    const i18n = {
      "en-US": {
        m: "minutes ago",
        h: "hours ago",
        d: "days ago",
        mon: "months ago",
        y: "years ago",
        now: "just now"
      },
      "zh-CN": {
        m: "分钟以前",
        h: "小时以前",
        d: "天以前",
        mon: "月以前",
        y: "年以前",
        now: "刚刚"
      },
      "de-DE": {
        m: "分前",
        h: "時間前",
        d: "日前",
        mon: "ヶ月前",
        y: "年前",
        now: "ちょうど今"
      }
    };

    const lang = i18n[locale];

    const stpAgo = new Date(ago).getTime();
    const stpNow = new Date(now).getTime();
    const stpDiffer = stpNow - stpAgo;
    // 1 s
    const s1 = 1000;
    // 1 m
    const m1 = s1 * 60;

    // 1 hour
    const h1 = m1 * 60;

    // 1 day
    const d1 = h1 * 24;

    // 1 month
    const mon1 = d1 * 30;

    // 1 year
    const y1 = mon1 * 12;
    if (stpDiffer < h1) {
      // min
      const min = stpDiffer / m1;
      return Math.floor(min) ? `${Math.floor(min)} ${lang.m}` : lang.now;
    }

    if (stpDiffer < d1) {
      // hour
      const hour = stpDiffer / h1;
      return `${Math.floor(hour)} ${lang.h}`;
    }

    if (stpDiffer < mon1) {
      // day
      const day = stpDiffer / d1;
      return `${Math.floor(day)} ${lang.d}`;
    }

    if (stpDiffer < y1) {
      // month
      const month = stpDiffer / mon1;
      return `${Math.floor(month)} ${lang.mon}`;
    }

    // year
    const year = stpDiffer / y1;
    return `${Math.floor(year)} ${lang.y}`;
  }
}
